var express = require('express');
var router=express.Router();
const {request, response} = require("express");
const{ Sequelize,DataTypes } = require('sequelize');
const jwt = require("jsonwebtoken");
const orm = require('../util/connect').orm()

const user = orm.import('../sequelize/models/user.model');
const login = orm.import('../sequelize/models/login.model');
const employee = orm.import('../sequelize/models/employee.model');
const consumer = orm.import('../sequelize/models/consumer.model');

//获取用户信息
router.get('/myProfile',(req,res)=>{
    const myuid=req.user.uid;
    const myIdentity =req.user['user.identity'];
    if(myIdentity == '普通用户'){
        user.findOne({
            where:{uid:myuid},
            attributes:['identity','tel','real_name','area'],
            include:[
                {
                model:user.hasOne(login, {
                    foreignKey: 'uid',
                    sourceKey: 'uid',
                    onUpdate: 'CASCADE',
                    onDelete: 'CASCADE'
                }),
                attributes:['user_name']
            }],
            raw:true
        }).catch(error=>{
            console.log(error)
        })
            .then(result=>{
                console.log(result)
                if(result !=null){
                    res.send({
                        code:200,
                        msg:"查询成功",
                        data:result
                    })
                }else{
                    res.send({
                        code:500,
                        msg:'查询失败'
                    })
                }
            })
        return
    }
    if(myIdentity == '员工'){
        console.log('开始查找')
        user.findOne({
            where:{uid:myuid},
            attributes:['uid','identity','tel','real_name','area'],
            include:[{
                association: user.hasOne(employee, {
                    foreignKey: 'uid',
                    sourceKey: 'uid',
                    onUpdate: 'CASCADE',
                    onDelete: 'CASCADE'
                }),
                attributes:['department','is_admin','is_approved']
            },{
                association:user.hasOne(login, {
                    foreignKey: 'uid',
                    sourceKey: 'uid',
                    onUpdate: 'CASCADE',
                    onDelete: 'CASCADE'
                }),
                attributes:['user_name']
            }],
            raw:true
        }).catch(error=>{
            console.log(error)
        })
            .then(result=>{
                if(result !=null){
                    console.log(result)
                    res.send({
                        code:200,
                        msg:"查询成功",
                        data:result
                    })
                }else{
                    res.send({
                        code:500,
                        msg:'查询失败'
                    })
                }
            })
        return
    }

})
//获取用户列表
router.get('/list',(req,res)=>{
    user.findAll({
        where:{
            identity:'普通用户'
        },
        attributes:['real_name'],
        include:[{
            association: user.hasOne(consumer, {
                foreignKey: 'uid',
                sourceKey: 'uid',
                onUpdate: 'CASCADE',
                onDelete: 'CASCADE'
            }),
            attributes:['address']
        }],
        raw:true
    })
        .then(result=>{
            if(result !=null){
                res.send({
                    code:200,
                    msg:"查询成功",
                    data:result
                })
            }else{
                res.send({
                    code:500,
                    msg:'查询失败'
                })
            }
        })
})
//获取员工信息
router.get('/employeeInfo',(req,res)=>{
    if(req.user['user.identity'] == '普通用户'){
        res.send({
            code:405,
            msg:"您无权限进行此操作",
        })
        return
    }
    user.findAll({
        where:{identity:'员工'},
        attributes:['real_name'],
        include:[{
            association: user.hasOne(employee, {
                foreignKey: 'uid',
                sourceKey: 'uid',
                onUpdate: 'CASCADE',
                onDelete: 'CASCADE'
            }),
            model:employee,
            attributes:['department','is_admin']
        }],
        raw:true
    })
        .then(result =>{
            if(result !=null){
                res.send({
                    code:200,
                    msg:"查询成功",
                    data:result
                })
            }else{
                res.send({
                    code:401,
                    msg:'查询列表为空'
                })
            }
        })
})
//更新用户信息
router.post('/updateUser',(req,res)=>{
    const {userdata}=req.body.modifyformData;
    console.log(userdata)
    user.update({
        identity:userdata.identity,
        tel:userdata.tel,
        real_name:userdata.real_name,
        area:userdata.area,
        login:{
            user_name:userdata.username
        }
    },{
        raw:true,
        include:[{
            association: user.hasOne(login, {
                foreignKey: 'uid',
                sourceKey: 'uid',
                onUpdate: 'CASCADE',
                onDelete: 'CASCADE'
            }),
            as:'login'
        }]
    }).then(result=>{
        res.send({
            code:200,
            msg:'更新信息成功',
            data:result
        })
    }).catch(error=>{
        res.send({
            code:500,
            msg:'更改失败'
        })
    })
    return

})
//获取用户地域分布
//select area,count(area) as area_num from user_info group by area;
router.get('/area',async (req,res)=>{
    const area = await user.findAll({
        attributes:[
            'area',
            [orm.fn('COUNT', orm.col('area')), 'area_num'],
        ],
        group:'area',
        raw:true
    })
    res.send({
        code:200,
        msg:"查询成功",
        data:area
    })
        // .then(result=>{
        //     if(result !=null){
        //         console.log(result);
        //         res.send({
        //             code:200,
        //             msg:"查询成功",
        //             data:result
        //         })
        //     }else{
        //         res.send({
        //             code:500,
        //             msg:'查询失败'
        //         })
        //     }
        // })
})
//注册接口
router.post('/register',(req,res) =>{
    const {data} = req.body;
    //检查是否已存在
    if(data == null){
        console.log('输入为空')
        res.send({
            code:500,
            msg:'注册发生错误'
        })
        return
    }
    if(data.identity == 'staff'){
        user.create({
                uid:0,
                identity:'员工',
                tel:data.tel,
                real_name:data.real_name,
                area:data.area,
                login:{
                    uid:0,
                    user_name:data.user_name,
                    pwd:data.pwd
                },
                employee:{
                    uid:0,
                    real_name:data.real_name,
                    department:data.department,
                    is_approved:'未审核'
                }
            },{
                raw:true,
                include:[{
                    association: user.hasOne(login, {
                        foreignKey: 'uid',
                        sourceKey: 'uid',
                        onUpdate: 'CASCADE',
                        onDelete: 'CASCADE'
                    }),
                    as:'login'
                },{
                    model:employee,
                    as:'employee'
                }],
            }
        ).then(result =>{
            if(result !=null){
                res.send({
                    code:200,
                    msg:"添加成功"
                })
            }else{
                res.send({
                    code:500,
                    msg:'添加失败'
                })
            }
            return
        }).catch((err)=>{
            console.log(err)
        })
    }else if(data.identity == 'cilent') {
        user.create({
                uid: 0,
                identity: '普通用户',
                tel: data.tel,
                real_name: data.real_name,
                area: data.area,
                login: {
                    uid: 0,
                    user_name: data.user_name,
                    pwd: data.pwd
                },
                consumer:{
                    uid:0,
                    address:data.address
                }
            }, {
                raw: true,
                include: [{
                    association: user.hasOne(login, {
                        foreignKey: 'uid',
                        sourceKey: 'uid',
                        onUpdate: 'CASCADE',
                        onDelete: 'CASCADE'
                    }),
                    as: 'login'
                },{
                    model:consumer,
                    as:'consumer'
                }],
            }
        ).then(result => {
            if (result != null) {
                res.send({
                    code: 200,
                    msg: "添加成功"
                })
            } else {
                res.send({
                    code: 500,
                    msg: '添加失败'
                })
            }
            return
        })
    }
})

module.exports=router;

